package com.xuecheng.messagesdk.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

@Configuration
public class MessageExecutorConfig {
    @Bean("messageTaskExecutor")
    public Executor messageTaskExecutor(){
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(3);        //设置核心线程数
        executor.setMaxPoolSize(5);         //设置最大线程数
        executor.setQueueCapacity(100);     //设置阻塞队列容量
        executor.setThreadNamePrefix("message-executor-");  //指定线程名前缀
        //设置线程池拒绝策略为，当线程池无法处理新提交的任务时，直接抛异常(默认拒绝策略)
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy());

        //配置线程池关闭参数(ThreadPoolTaskExecutor是spring的，可以由spring管理)
        //这个是设置线程池关闭时，等待队列中的所有任务执行完毕再关闭
        executor.setWaitForTasksToCompleteOnShutdown(true);
        //这个是配合上面的参数使用的，最多等30秒，防止无限等待
        executor.setAwaitTerminationSeconds(30);

        executor.initialize();
        return executor;
    }
}
